import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import apiService from '../utils/api.js'
import { getGenderLabel, getTypeLabel, ARTIST_GENDER_OPTIONS, ARTIST_TYPE_OPTIONS, ARTIST_NATIONALITY_OPTIONS } from '../utils/constants.js'
import Pagination from '../components/Pagination.jsx'
import '../styles/pages.css'

function Artist() {
  const [artists, setArtists] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [pageSize, setPageSize] = useState(21)
  const [totalItems, setTotalItems] = useState(0)
  
  // 分类过滤状态
  const [selectedNationality, setSelectedNationality] = useState('')
  const [selectedGender, setSelectedGender] = useState('')
  const [selectedType, setSelectedType] = useState('')

  // 获取歌手列表
  const fetchArtists = async () => {
    setLoading(true)
    setError('')
    try {
      const response = await apiService.getArtists({
        page: currentPage,
        limit: pageSize,
        nationality: selectedNationality,
        gender: selectedGender,
        type: selectedType
      })
      
      // 模拟数据，因为API可能不可用
      if (!response || !response.data || response.data.data.length === 0) {
        // 生成模拟数据作为备用
        setArtists([])
        setTotalPages(0) // 模拟总页数
        setTotalItems(0) // 模拟总记录数
      } else {
        setArtists(response.data.data)
        setTotalPages(response.data.meta.totalPages || 1)
        setTotalItems(response.data.meta.total || 0)
      }
    } catch (err) {
      console.error('获取歌手列表失败:', err)
      setError('获取歌手列表失败，请稍后再试')
      // 生成模拟数据作为备用
      setArtists([])
      setTotalPages(0) // 模拟总页数
      setTotalItems(0) // 模拟总记录数
    } finally {
      setLoading(false)
    }
  }

  // 切换页面
  const handlePageChange = (page) => {
    if (page > 0 && page <= totalPages) {
      setCurrentPage(page)
    }
  }
  
  // 分类过滤处理
  const handleFilterChange = (filterType, value) => {
    setCurrentPage(1) // 重置到第一页
    switch(filterType) {
      case 'nationality':
        setSelectedNationality(value)
        break
      case 'gender':
        setSelectedGender(value)
        break
      case 'type':
        setSelectedType(value)
        break
      default:
        break
    }
  }
  
  // 重置所有过滤条件
  const resetFilters = () => {
    setSelectedNationality('')
    setSelectedGender('')
    setSelectedType('')
    setCurrentPage(1)
  }
  
  // 渲染歌手列表
  const renderArtists = () => {
    return (
      <div className="artist-grid">
        {artists.map((artist) => (
          <Link to={`/artist/${artist.id}`} className="artist-card" style={{ textDecoration: 'none', color: 'inherit' }}>
            <img 
              src={artist.avatarUrl || `https://via.placeholder.com/200?text=${encodeURIComponent(artist.name)}`} 
              alt={artist.name}
              className="artist-avatar"
            />
            <h3 className="artist-name">{artist.name}</h3>
            <div className="artist-info">
              <span className="artist-gender">{getGenderLabel(artist.gender)}</span>
              <span className="artist-type">{getTypeLabel(artist.type)}</span>
            </div>
          </Link>
        ))}
      </div>
    );
  }

  // 组件加载时和页面变化时获取数据
  useEffect(() => {
    fetchArtists()
  }, [currentPage, pageSize, selectedNationality, selectedGender, selectedType])

  return (
    <div className="artist-page">
        
        {/* 总数统计 */}
        <div className="total-count">
          共{artists.length}个歌手
        </div>
        
        {/* 过滤器区域 */}
      <div className="artist-filters">
        {/* 地区过滤器 */}
        <div className="filter-group">
          <span className="filter-label">歌手分类:</span>
          <button 
            className={`filter-btn ${selectedNationality === '' ? 'active' : ''}`}
            onClick={() => handleFilterChange('nationality', '')}
          >
            全部
          </button>
          {ARTIST_NATIONALITY_OPTIONS.filter(opt => opt.value).map(option => (
            <button
              key={option.value}
              className={`filter-btn ${selectedNationality === option.value ? 'active' : ''}`}
              onClick={() => handleFilterChange('nationality', option.value)}
            >
              {option.label}
            </button>
          ))}
        </div>
        
        {/* 性别过滤器 */}
        <div className="filter-group">
          <span className="filter-label">性别:</span>
          <button 
            className={`filter-btn ${selectedGender === '' ? 'active' : ''}`}
            onClick={() => handleFilterChange('gender', '')}
          >
            全部
          </button>
          {ARTIST_GENDER_OPTIONS.filter(opt => opt.value).map(option => (
            <button
              key={option.value}
              className={`filter-btn ${selectedGender === option.value ? 'active' : ''}`}
              onClick={() => handleFilterChange('gender', option.value)}
            >
              {option.label}
            </button>
          ))}
        </div>
        
        {/* 类型过滤器 */}
        <div className="filter-group">
          <span className="filter-label">歌手类型:</span>
          <button 
            className={`filter-btn ${selectedType === '' ? 'active' : ''}`}
            onClick={() => handleFilterChange('type', '')}
          >
            全部
          </button>
          {ARTIST_TYPE_OPTIONS.filter(opt => opt.value).map(option => (
            <button
              key={option.value}
              className={`filter-btn ${selectedType === option.value ? 'active' : ''}`}
              onClick={() => handleFilterChange('type', option.value)}
            >
              {option.label}
            </button>
          ))}
        </div>
        
        {/* 重置按钮 */}
        {selectedNationality || selectedGender || selectedType ? (
          <button className="reset-btn" onClick={resetFilters}>
            重置筛选
          </button>
        ) : null}
      </div>

      {/* 错误信息显示 */}
      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {/* 加载状态 */}
      {loading ? (
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      ) : (
        <>
          {artists.length > 0 ? (
            <div className="artists-container">
              {/* 歌手列表 */}
              {renderArtists()}
            </div>
          ) : (
            <div className="empty-state">
              <p>暂无歌手数据</p>
            </div>
          )}
        </>
      )}

      {/* 分页控件 - 使用Pagination组件 */}
      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          totalItems={totalItems}
          itemsPerPage={pageSize}
          onPageChange={handlePageChange}
        />
      )}
    </div>
  )
}

export default Artist